<?php
namespace App\Service;

use Elasticsearch\ClientBuilder;

class Es
{
    protected $client;

    /**
     * Es constructor.
     *
     */
    public function __construct()
    {
        $this->client = ClientBuilder::create()->setHosts([
            [
                'host'   => config('es.host'),
                'port'   => config('es.port'),
                'scheme' => config('es.scheme'),
                'user'   => config('es.user'),
                'pass'   => config('es.pass')
            ]
        ])->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
            ->setRetries(10)->build();
    }

    /**
     * 创建中文分词索引
     */
    public function createIndex()
    {
        $params = [
            'index' => 'house'
        ];
        // Create the index
        $response = $this->client->indices()->create($params);
        //指定分词（别忘了粘上面的$client）
        $params = [
            'index' => 'my_index',
            'body' => [
                'settings' => [
                    'number_of_shards' => 3,
                    'number_of_replicas' => 2
                ],
                'mappings' => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'house_name' => [
                            'type' => 'text',
                            "analyzer" => "ik_max_word",
                            "search_analyzer" => "ik_max_word"
                        ]
                    ]
                ]
            ]
        ];
        // Create the index with mappings and settings now
        $response = $this->client->indices()->create($params);
        return $response;
    }

    /**
     * @param $data
     * @return array|callable
     * 添加Es
     */
    public function addEsData($data)
    {
        if (!$data){
            return '请传入添加数据';
        }
        if (!is_array($data)){
            $data = $data->toArray();
        }
        $params = [
            'index' => 'house',
            'type' => '_doc',
            'id' => $data['id'],
            'body' => $data
        ];
        $response = $this->client->index($params);
        return $response;
    }

    /**
     * @param $id
     * @return array
     * 删除ES数据
     */
    public function deleteEsData($id)
    {
        $params = ['index' => 'house','id'=>$id];
        $response = $this->client->indices()->delete($params);
        return $response;
    }

    /**
     * @param $id
     * @param $data
     * @return array|callable|string
     * 修改ES数据
     */
    public function updateEsData($id,$data)
    {
        if (!$data){
            return '请传入修改数据';
        }
        if (!is_array($data)){
            $data = $data->toArray();
        }
        $params = [
            'index' => 'house',
            'type' => '_doc',
            'id' => $id,
            'body' => $data
        ];
        $response = $this->client->update($params);
        return $response;
    }

    /**
     * @param $house_name
     * @return array|callable
     * 高亮搜索
     */
    public function  newHouseEs($house_name)
    {
        $params = [
            'index' => 'house',
            'body' => [
                'query' => [
                    'match' => [
                        'house_name' => $house_name
                    ]
                ],
                'highlight' => [
                    'pre_tags' => ["<em style='color: red'>"],
                    'post_tags' => ["</em>"],
                    'fields' => [
                        "house_name" => new \stdClass()
                    ]
                ]
            ]
        ];
        $response = $this->client->search($params);
        return $response;
    }

    public function getData($house_name)
    {
        $params = [
            'index' => 'house',
            'body' => [
                'query' => [
                    'match' => [
                        'house_name' => $house_name
                    ]
                ]
            ]
        ];
        $response = $this->client->search($params);
        return array_column($response['hits']['hits'],'_source');
    }
}
